//
//  ICostDTViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/11/27.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

class ICostDTViewController: BaseViewController,UIScrollViewDelegate {
    
    
    var maxwidth: CGFloat = 500
    var maxheight: CGFloat = 375
    
    var other = false
    
    var widthunit = UIScreen.main.bounds.size.width / 25//将屏幕分为25份
    var heightunit = (UIScreen.main.bounds.size.height - 64) / 9 //将屏幕分为9分
    
    typealias NameDatas = (String,Array<JSON>)
    
    var datas: [NameDatas] = []
    
    override func path(for name: String) -> String {
        return IncomeAndCostPlan
    }
    
    override var names: Array<String>{
        get{
            return ["haha"]
        }
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        return ["planType": plantype,"orgCode": orgCode]
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    @objc func tolist(btn: UIButton)->Void{
        let index = btn.tag - 1000
        if index < datas.count {
            let item = datas[index]
            let org = item.1[0].contents?["orgCode"]?.rawString() ?? ""
            let list = IncomeCostListViewController()
            list.title = "综合计划列表"
            list.orgCode = org
            list.planType = self.plantype
            self.push(destination: list)
        }
    }
    
    override func success(for name: String) -> NetSuccess {
        func suc(json: JSON)->Void{
            if let success = json.contents?["success"]?.bool {
                if success == true  {
                    if let data = json.contents?["data"]?.array {
                        source = data
                        print(source)
                        let names = source.map { (json) -> String in
                            return json.contents?["deptName"]?.rawString() ?? ""
                            }.filterDuplicates({$0})
                        
                        for name in names {
                            datas.append((name,source.filter({ (json) -> Bool in
                                return json.contents?["deptName"]?.rawString() == name
                            })))
                        }
                        //名字又了
                        let widths: [CGFloat] = [widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * CGFloat(3),widthunit * CGFloat(2),widthunit * CGFloat(3),widthunit * CGFloat(2),widthunit * CGFloat(3),widthunit * CGFloat(2)]
                        for i in  0 ..< datas.count {
                            let data = datas[i]
                            let namelabel = button(with: data.0)
                            namelabel.left = 0
                            namelabel.alpha = 0.7
                            namelabel.top = CGFloat(heightunit * CGFloat(2) * CGFloat(i))
                            namelabel.width = widthunit * CGFloat(3)
                            namelabel.height = heightunit * CGFloat(2)
                            namelabel.tag = 1000 + i
                            namelabel.addTarget(self, action: #selector(tolist(btn:)), for: .touchUpInside)
                            leftscroll.addSubview(namelabel)
                            leftscroll.contentSize = CGSize.init(width: widthunit * CGFloat(3), height: namelabel.bottom)//左边的标签先加上
                            //开始加右边的标签
                            for j in 0 ..< data.1.count {
                                if j == 0 {
                                    let one = data.1[0]
                                    let incomelbl = label(width: "收入")
                                    incomelbl.left = 0
                                    incomelbl.top = CGFloat(heightunit * CGFloat(2) * CGFloat(i))
                                    incomelbl.width = widthunit
                                    incomelbl.height = heightunit
                                    incomelbl.alpha = 0.7
                                    contentscroll.addSubview(incomelbl)
                                    //死标签先加上
                                    let plan = String((one.contents?["planMoney"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    let budget = String((one.contents?["budget"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio1 = String(format: "%.2f", Double((one.contents?["budget"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio1 == "inf%" || ratio1 == "nan%" || ratio1 == "nan" {
                                        ratio1 = "0.00%"
                                    }
                                    let projContract = String((one.contents?["projContract"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio2 =  String(format: "%.2f", Double((one.contents?["projContract"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio2 == "inf%" || ratio2 == "nan%" || ratio2 == "nan" {
                                        ratio2 = "0.00%"
                                    }
                                    let projInvoice = String((one.contents?["projInvoice"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio3 = String(format: "%.2f", Double((one.contents?["projInvoice"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio3 == "inf%" || ratio3 == "nan%" || ratio3 == "nan" {
                                        ratio3 = "0.00%"
                                    }
                                    let projPayment = String((one.contents?["projPayment"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio4 = String(format: "%.2f", Double((one.contents?["projPayment"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio4 == "inf%" || ratio4 == "nan%" || ratio4 == "nan" {
                                        ratio4 = "0.00%"
                                    }
                                    let texts: [String] = [plan,budget,ratio1,projContract,ratio2,projInvoice,ratio3,projPayment,ratio4]

                                    for k in 0 ..< texts.count {
                                        let text = label(width: texts[k])
                                        text.width = widths[k]
                                        text.top = CGFloat(heightunit * CGFloat(2)) * CGFloat(i)
                                        var left: CGFloat = 0
                                        for h in 0 ..< k {
                                            left = left + (widths[h])
                                        }
                                        text.left = left + incomelbl.left + incomelbl.width
                                        text.height = heightunit
                                        contentscroll.addSubview(text)
                                    }
                                } else {
                                    let one = data.1[1]
                                    let incomelbl = label(width: "支出")
                                    incomelbl.alpha = 0.7
                                    incomelbl.left = 0
                                    incomelbl.top = CGFloat(heightunit * CGFloat(2) * CGFloat(i) + heightunit)
                                    incomelbl.width = widthunit
                                    incomelbl.height = heightunit
                                    contentscroll.addSubview(incomelbl)
                                    let plan = String((one.contents?["planMoney"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    let budget = String((one.contents?["budget"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio1 = String(format: "%.2f", Double((one.contents?["budget"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100)
                                    if ratio1 == "inf%" || ratio1 == "nan%" || ratio1 == "nan" {
                                        ratio1 = "0.00%"
                                    }
                                    let projContract = String((one.contents?["projContract"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio2 =  String(format: "%.2f", Double((one.contents?["projContract"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio2 == "inf%" || ratio2 == "nan%" || ratio2 == "nan" {
                                        ratio2 = "0.00%"
                                    }
                                    let projInvoice = String((one.contents?["projInvoice"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio3 = String(format: "%.2f", Double((one.contents?["projInvoice"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio3 == "inf%" || ratio3 == "nan%" || ratio3 == "nan" {
                                        ratio3 = "0.00%"
                                    }
                                    let projPayment = String((one.contents?["projPayment"]?.int ?? 0) / 1000000).rmbformat.trimmingCharacters(in: CharacterSet.init(charactersIn: "¥"))
                                    var ratio4 = String(format: "%.2f", Double((one.contents?["projPayment"]?.int ?? 0)) / Double((one.contents?["planMoney"]?.int ?? 0)) * 100) + "%"
                                    if ratio4 == "inf%" || ratio4 == "nan%" || ratio4 == "nan" {
                                        ratio4 = "0.00%"
                                    }
                                    let texts: [String] = [plan,budget,ratio1,projContract,ratio2,projInvoice,ratio3,projPayment,ratio4]

                                    for k in 0 ..< texts.count {
                                        let text = label(width: texts[k])
                                        text.width = widths[k]
                                        text.top = CGFloat(heightunit * 2) * CGFloat(i) + heightunit
                                        var left: CGFloat = 0
                                        for h in 0 ..< k {
                                            left = left + (widths[h] )
                                        }
                                        text.left = left + incomelbl.left + incomelbl.width
                                        text.height = heightunit
                                        contentscroll.addSubview(text)
                                    }
                                }
                            }
                            
                        }
                        //详情
                        contentscroll.contentSize = CGSize.init(width: topscroll.contentSize.width, height: leftscroll.contentSize.height)
                        //加线段
                        
                        let topview = UIView()
                        topview.frame = CGRect.init(origin: CGPoint(x: 0,y: 0), size: CGSize(width: self.view.width,height: 1))
                        self.view.addSubview(topview)
                        
                        let view = UIView()
                        view.backgroundColor = UIColor.hex("1C90D1")
                        view.frame = CGRect.init(origin: CGPoint(x: 0,y: heightunit), size: CGSize(width: self.view.width,height: 1))
                        self.view.addSubview(view)
                        
                        let vertical = UIView()
                        vertical.backgroundColor = UIColor.hex("1C90D1")
                        vertical.frame = CGRect.init(origin: CGPoint(x: widthunit * CGFloat(3),y: 0), size: CGSize(width: 1,height: self.view.height))
                        self.view.addSubview(vertical)
                        for i in 1 ..< datas.count {
                            let view = UIView()
                            view.backgroundColor = UIColor.hex("1C90D1")
                            view.frame = CGRect.init(origin: CGPoint(x: 0,y: heightunit * CGFloat(2) * CGFloat(i)), size: CGSize(width: widthunit * CGFloat(3),height: 1))
                            leftscroll.addSubview(view)
                        }
                        let widths1: [CGFloat] = [widthunit,widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * CGFloat(3),widthunit * CGFloat(2),widthunit * CGFloat(3),widthunit * CGFloat(2),widthunit * CGFloat(3),widthunit * CGFloat(2)]
                        for i in 0 ..< 9 {
                            let view = UIView()
                            view.backgroundColor = UIColor.hex("1C90D1")
                            var totalx: CGFloat = 0.0
                            for j in 0 ... i {
                                totalx = totalx + widths1[j]
                            }
                            view.frame = CGRect.init(origin: CGPoint(x: totalx,y: 0), size: CGSize(width: 1,height: heightunit))
                            topscroll.addSubview(view)
                        }
                        for i in 0 ..< 9 {
                            let vertical = UIView()
                            vertical.backgroundColor = UIColor.hex("1C90D1")
                            var totalx: CGFloat = 0.0
                            for j in 0 ... i {
                                totalx = totalx + widths1[j]
                            }
                            vertical.frame = CGRect.init(origin: CGPoint(x: totalx,y: 0), size: CGSize(width: 1,height: maxheight - maxheight / 11))
                            contentscroll.addSubview(vertical)
                        }
                        for i in 1 ..< datas.count * 2 {
                            let horizontal = UIView()
                            horizontal.backgroundColor = UIColor.hex("1C90D1")
                            horizontal.frame = CGRect.init(origin: CGPoint(x: 0,y: heightunit * CGFloat(i)), size: CGSize(width: maxwidth - maxwidth / 25 * 3,height: 1))
                            contentscroll.addSubview(horizontal)
                        }
                    }
                }
                
            } else {
                alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        return suc
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        switch scrollView {
        case topscroll:
            contentscroll.contentOffset = CGPoint.init(x: topscroll.contentOffset.x, y: contentscroll.contentOffset.y)//topscroll.contentOffset
            break
        case leftscroll:
            contentscroll.contentOffset = CGPoint.init(x: contentscroll.contentOffset.x, y: leftscroll.contentOffset.y)
            break
        default:
            topscroll.contentOffset = CGPoint.init(x: contentscroll.contentOffset.x, y: 0)//contentscroll.contentOffset
            
            leftscroll.contentOffset = CGPoint.init(x: 0, y: contentscroll.contentOffset.y)
            
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.shadowImage = nil
        self.recovernavigationbar()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let image = UIColor.hex("1C90D1").image(size: CGSize(width: UIScreen.main.bounds.size.width, height: 1))
        self.navigationController?.navigationBar.shadowImage = image
        self.navigationController?.navigationBar.setBackgroundImage(UIColor.hex("0B1A36").image(size: CGSize(width: UIScreen.main.bounds.size.width, height: 64)), for: .default)
        let back = UIBarButtonItem.init(image: UIImage.init(named: "icon_nav_back")!, style: .plain, target: self, action: #selector(pop))
        self.navigationItem.leftBarButtonItem = back
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        self.navigationController?.navigationBar.barTintColor = .white
        self.navigationController?.navigationBar.tintColor = .white
        let number = NSNumber.init(value: UIInterfaceOrientation.unknown.rawValue)
        UIDevice.current.setValue(number, forKey: "orientation")
        let orientationTarget = NSNumber.init(value: UIInterfaceOrientation.landscapeLeft.rawValue)
        UIDevice.current.setValue(orientationTarget, forKey: "orientation")
    }
    
    var alreadylayout = false
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        maxwidth = 1000
        maxheight = self.view.height
        widthunit = maxwidth / 25//UIScreen.main.bounds.size.width / 25//将屏幕分为25份
        heightunit = maxheight / 11//(UIScreen.main.bounds.size.height - 64) / 9 //将屏幕分为9分
        topscroll.frame = CGRect.init(origin: CGPoint.init(x: widthunit * CGFloat(3), y: 0), size: CGSize.init(width: self.view.width - widthunit * CGFloat(3), height: heightunit))
        leftscroll.frame = CGRect.init(origin: CGPoint.init(x: 0, y: heightunit), size: CGSize.init(width: widthunit * CGFloat(3), height: self.view.height - heightunit))
        contentscroll.frame = CGRect.init(origin: CGPoint.init(x: widthunit * CGFloat(3), y: heightunit), size: CGSize.init(width: self.view.width - widthunit * CGFloat(3), height: self.view.height - heightunit))
        if alreadylayout == false {
            alreadylayout = true
            let bumen = label(width: "部门")
            self.view.addSubview(bumen)
            bumen.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: widthunit * 3, height: heightunit))
            let widths: [CGFloat] = widthvalues
            let labels: [String] = titlelabels
            var left: CGFloat = 0
            for i in 0 ..< widths.count {
                if labels.count > i {
                    let lbl = label(width: labels[i])
                    lbl.left = left
                    lbl.height = heightunit
                    lbl.top = 0
                    lbl.width = widths[i]
                    left = left + widths[i]
                    topscroll.addSubview(lbl)
                }
            }
            topscroll.contentSize = CGSize.init(width: widthunit * 22, height: 0)
        }
    }
    
    override var shouldAutorotate: Bool{
        get{
            return true
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get{
            return UIInterfaceOrientationMask.landscape
        }
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        get{
            return UIInterfaceOrientation.landscapeLeft
        }
    }
    
    var plantype = "0"
    var orgCode = ""
    var source: [JSON] = []
    
    let topscroll = UIScrollView()
    let leftscroll = UIScrollView()
    let contentscroll = UIScrollView()
    
    func label(width text: String)->UILabel{
        let bumen = UILabel()
        bumen.alpha = 0.7
        bumen.text = text
        bumen.textColor = UIColor.white
        bumen.backgroundColor = UIColor.hex("0B1A36")
        bumen.font = UIFont.systemFont(ofSize: 16)
        bumen.textAlignment = .center
        bumen.numberOfLines = 0
        bumen.adjustsFontSizeToFitWidth = true
        return bumen
    }
    
    func button(with text: String)->UIButton{
        let button = UIButton.init(type: .system)
        button.titleLabel?.numberOfLines = 0
        button.setTitle(text, for: .normal)
        button.setTitleColor(UIColor.green, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        return button
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.hex("0B1A36")
        leftscroll.delegate = self
        leftscroll.backgroundColor = UIColor.hex("0B1A36")
        leftscroll.bounces = false
        topscroll.delegate = self
        topscroll.bounces = false
        topscroll.backgroundColor = UIColor.hex("0B1A36")
        contentscroll.delegate = self
        contentscroll.bounces = false
        contentscroll.backgroundColor = UIColor.hex("0B1A36")
        leftscroll.showsVerticalScrollIndicator = false
        topscroll.showsHorizontalScrollIndicator = false
        contentscroll.showsHorizontalScrollIndicator = false
        contentscroll.showsVerticalScrollIndicator = false
        
        self.view.addSubview(leftscroll)
        self.view.addSubview(topscroll)
        self.view.addSubview(contentscroll)
        
        
        self.load(with: self.names[0])
        // Do any additional setup after loading the view.
    }
    
    var widthvalues: [CGFloat] {
        get{
            if other == false {
                return [widthunit,widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * 3,widthunit * CGFloat(2),widthunit * 3,widthunit * CGFloat(2),widthunit * 3,widthunit * CGFloat(2)]
            } else {
                return [widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * CGFloat(2),widthunit * 3,widthunit * CGFloat(2),widthunit * 3,widthunit * CGFloat(2),widthunit * 3,widthunit * CGFloat(2)]
            }
        }
    }
    
    var titlelabels: [String] {
        get{
            return ["分项","综合计划","立项预算","转化比例","项目执行按合同","执行比例","项目执行发票","执行比例","项目执行按收付款","执行比例"]
        }
    }

}
